package org.flower.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @Discription 字符编码过滤器
 * @author Aizen
 * @date 2021-12-9
 **/
public class CharSetFilter implements Filter {

    /**
     * 定义变量接收初始化的值
     */
    private static String encoding;

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
        // 设置字符编码链锁
        request.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset=utf-8");
        chain.doFilter(request, response);
    }

    /**
     * 初始化
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig config) throws ServletException {
        // 接收web.xml配置文件中的初始参数
        encoding = config.getInitParameter("CharsetEncoding");
    }

}